package org.example.consumer.controller;

import org.example.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Date: 2024/9/27
 * @Author: Administrator
 * @ClassName: OrderController
 * @Description: comment here
 */

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/add/{id}")
    public Goods addGoods(@PathVariable("id") Integer id) {
        //业务逻辑
        //1查询商品
        //2减库存
        //3支付
        //4物流
        //直接调用
//        String targetUrl = "http://localhost:8000/goods/" + id;
//        Goods goods = restTemplate.getForObject(targetUrl, Goods.class);

        // 服务发现——向注册中心问询实例
        List<ServiceInstance> instances = discoveryClient.getInstances("zookeeper-provider");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        // 通过某个策略拿到一个实例
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        System.out.println("host = " + host);
        System.out.println("port = " + port);

        String url = "http://" + host + ":" + port + "/goods/" + id;
        Goods goods = restTemplate.getForObject(url, Goods.class);

        return goods;
    }
}
